<!--物料维护-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类别" prop="category">
        <el-input v-model="queryParams.category" placeholder="请输入类别" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="关键参数" prop="keyParameters">
        <el-input v-model="queryParams.keyParameters" placeholder="请输入关键参数" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="物料级别" prop="itemLevel">
        <el-input v-model="queryParams.itemLevel" placeholder="请输入物料级别" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="原厂型号" prop="originalModel">
        <el-input v-model="queryParams.originalModel" placeholder="请输入原厂型号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备注1" prop="remark1">
        <el-input v-model="queryParams.remark1" placeholder="请输入备注1" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="备注2" prop="remark2">
        <el-input v-model="queryParams.remark2" placeholder="请输入备注2" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="简称" prop="shortName">
        <el-input v-model="queryParams.shortName" placeholder="请输入简称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用量" prop="dosage">
        <el-input v-model="queryParams.dosage" placeholder="请输入用量" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['gyl:materialmaintenance:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['gyl:materialmaintenance:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                   v-hasPermi="['gyl:materialmaintenance:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   v-hasPermi="['gyl:materialmaintenance:export']">导出</el-button>
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport">导入</el-button>
      </el-col>
      <EasyTable ref="childRef" :tableData="materialmaintenanceList" :columns="tableColumn" :Shuju="Shuju" @listen="handleSelectionChange" @changeList="rowsol">
        <vxe-column title="操作" width="200" show-overflow>
          <template #default="{ row }">
            <vxe-button type="text" icon="vxe-icon-edit" @click="handleUpdate(row)">编辑</vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" @click="handleDelete(row)">删除</vxe-button>
          </template>
        </vxe-column>
      </EasyTable>
    </el-row>
<!--    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"-->
<!--                @pagination="getList" />-->
    <div style="display: flex; height: 30px; justify-content:flex-end">
      <div class="Size">字体大小</div>
      <el-input class="Einput" v-model="Shuju.fontSize" placeholder="字体大小" clearable @blur="blurs"></el-input>
      <div class="Size">行高</div>
      <el-input class="Einput" v-model="Shuju.Height" placeholder="行高" clearable @blur="blurs">
      </el-input>
      <pagination v-show="total > 0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList" style="width: 800px ; margin-top: -10px"/>
    </div>
    <!--    修改某一列数据-->
    <el-dialog :visible.sync="opens" width="500px" append-to-body :title="title">
      <el-form label-width="80px">
        <el-form-item label="修改值" prop="category">
          <el-input v-model="list.afterName" placeholder="请输入修改值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitList">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改物料维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="物料名称" prop="category">
          <MySelect
            placeholder="请选择物料名称"
            @editValue="editValue"
            valueType="category"
            :selectArray="categorys" />
        </el-form-item>
        <el-form-item label="类别" prop="materialName">
          <el-input :disabled="true" v-model="form.category"/>
        </el-form-item>
        <el-form-item label="物料级别" prop="itemLevel">
          <MySelect
            placeholder="请选择字母"
            @editValue="editValue"
            valueType="itemLevelFirst"
            :selectArray="zimus" />
            <MySelect
            placeholder="请选择数字"
            @editValue="editValue"
            valueType="itemLevelSecond"
            :selectArray="suzis"/>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <MySelect
            placeholder="请选择品牌"
            @editValue="editValue"
            valueType="brand"
            :selectArray = "brands" />
        </el-form-item>
        <el-form-item label="大类" prop="shortName">
          <MySelect
            placeholder="请选择大类"
            @editValue="editValue"
            valueType="daleis"
            :selectArray = "daleis" />
        </el-form-item>
        <el-form-item v-if="xiaoleiss.length!=0" label="小类" prop="shortName">
          <MySelect
            placeholder="请选择小类"
            @editValue="editValue"
            valueType="xiaoleiss"
            :selectArray = "xiaoleiss" />
        </el-form-item>
        <el-form-item v-if="leiItems.length!=0" label="选项配置" prop="shortName">
        <el-form :inline="true">
          <el-form-item :rules="{required: item.isRequire==='必选'?true:false, message: '必填项', trigger: 'blur'}" :key="item.id"  v-for="item in leiItems">
            <MyObject
            :selectArray="OptionsKeyValue[item.title]"
            :title="item.title"
            :isRequire="item.isRequire"
            :inputData="item.data"
            :id="item.id"
            @editLeisItemsData="editItemValue" />
          </el-form-item>
        </el-form>
        </el-form-item>
        <el-form-item label="原厂型号" prop="originalModel">
          <el-input v-model="form.originalModel" placeholder="请输入原厂型号" />
        </el-form-item>
        <el-form-item label="备注1" prop="remark1">
          <el-input v-model="form.remark1" placeholder="请输入备注1" />
        </el-form-item>
        <el-form-item label="备注2" prop="remark2">
          <el-input v-model="form.remark2" placeholder="请输入备注2" />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input v-model="form.shortName" placeholder="请输入简称" />
        </el-form-item>
        <el-form-item v-if="leiItems.length!=0" label="关键参数" prop="keyParameters">
          <el-input :disabled="true" v-model="keyParameters" placeholder="请输入关键参数" />
        </el-form-item>
        <!--  <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="用量" prop="dosage">
          <el-input v-model="form.dosage" placeholder="请输入用量" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMaterialmaintenance, getMaterialmaintenance, delMaterialmaintenance, addMaterialmaintenance, updateMaterialmaintenance,PutMaterialmaintenance } from "@/api/gyl/materialmaintenance";
import { getToken } from "@/utils/auth";
// 导入模板接口importTemplate
import { importTemplate } from "@/api/system/user";
import EasyTable from '@/components/EasyTable/index.vue'
import MySelect from './components/MySelect.vue'
import MyObject from './components/MyObject'
import { listMaterials } from '@/api/gyl/materials.js'
import { listRulesTotal } from '@/api/gyl/rules.js'
import { listGylvalueTotal } from '@/api/gyl/gylvalue.js' 
import { addShenhe } from '@/api/gyl/shenhe.js'

export default {
  name: "Materialmaintenance",
  components: {
    EasyTable,
    MySelect,
    MyObject
  },
  mounted(){
    this.getInitDataList()
    this.getGYLValueSelect()
  },
  watch:{
    'form.daleis':{
      handler(newValue,oldValue){
        this.xiaoleiss = []
        this.xiaoleis = []
        this.leiItems = []
        this.leiItemss = []
        this.totalList.forEach( (item,index1) => {
          item.forEach( itemObj => {
            if(itemObj.ruleValue === newValue) !this.xiaoleis.includes(item[1].ruleValue) && this.xiaoleis.push({index:index1,value:item[1].ruleValue})
          })
        })
        this.xiaoleis.forEach( item => !this.xiaoleiss.includes(item.value) && this.xiaoleiss.push(item.value))
      },
      deep:true
    },
    'form.xiaoleiss':{
      handler(newValue,oldValue){
        this.leiItems = []
        this.leiItemss = []
        
        this.xiaoleis.forEach( item => {
          if(this.form.xiaoleiss === item.value) return this.totalList[item.index].slice(2).forEach( item => !this.leiItemss.includes(item.elementName) && this.leiItems.push({id:item.id,title:item.elementName,data:'',isRequire:item.choice}) && this.leiItemss.push(item.elementName))
        })
      },
      deep:true
    },
    'open':{
      handler(){
        this.leiItems = []
        this.xiaoleiss = []
        this.xiaoleis = []
        this.leiItemss = []
      }
    }
  },
  data() {
    return {
      Shuju:{
        //表格字体大小
        fontSize:'12',
        Height:60,
      },
      opens:false,
      //修改列表参数
      list:{
        ids:[],
        //点击某一列的字段名称
        itemName:'',
        afterName:'',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料维护表格数据
      materialmaintenanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        category: null,
        materialCode: null,
        materialName: null,
        keyParameters: null,
        itemLevel: null,
        brand: null,
        originalModel: null,
        remark1: null,
        remark2: null,
        shortName: null,
        dosage: null
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/gyl/materialmaintenance/importData"
      },
      tableColumn: [
        //{ key: 0, type: 'seq', width: 60, fixed: null },
        { key: 1, type: 'checkbox', width: 50, fixed: null },
        { key: 2, field: 'category', title: '类别', },
        { key: 3, field: 'materialCode', title: '物料编码', },
        { key: 4, field: 'materialName', title: '物料名称', },
        { key: 5, field: 'keyParameters', title: '关键参数', },
        { key: 6, field: 'itemLevel', title: '物料级别', },
        { key: 7, field: 'brand', title: '品牌', },
        { key: 8, field: 'originalModel', title: '原厂型号', },
        { key: 9, field: 'remark1', title: '备注1', },
        { key: 10, field: 'remark2', title: '备注2', },
        { key: 11, field: 'shortName', title: '简称', },
      ],
      // 表单参数
      form: {
        daleis:null,
        itemLevelFirst:'',
        itemLevelSecond:''
      },
      // 表单校验
      rules: {},
      //分类的数组
      categorys:[],
      //品牌
      brands:[],
      //描述规则的总数据
      rulesList:[],
      //总数据
      totalList:[],
      //大类的所有值
      daleis:[],
      //小类的值
      xiaoleis:[],
      xiaoleiss:[],
      leiItems:[],
      leiItemss:[],
      leiItemsForm:{},
      //listMaterials回调接口的数组
      listMaterials:[],
      zimus:"ABCDEFGHIJKLMNOPQRSTUVWXYZ".split(''),
      suzis:[0,1,2,3,4,5,6,7,8,9],
      //选项配置的所有数据
      OptionsDefineTotals:[],
      //选项配置的 名称 以及 名称下的数据放在数组里面，以Key Value的形式存放
      OptionsKeyValue:[]
    };
  },
  computed: {
    keyParameters(){
      let data = [this.form.daleis,this.form.xiaoleiss]
      this.leiItems.forEach( item => data.push(item.data))
      return data.join(' ')
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物料维护列表 */
    getList() {
      this.loading = true;
      listMaterialmaintenance(this.queryParams).then(response => {
        this.materialmaintenanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        category: null,
        materialCode: null,
        materialName: null,
        keyParameters: null,
        itemLevel: null,
        brand: null,
        originalModel: null,
        remark1: null,
        remark2: null,
        shortName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        dosage: null,
        daleis:null,
        xiaoleiss:null
      };
      this.resetForm("form");
      this.opens=false;
      this.list={
        ids:[],
        itemName: '',
        afterName: ''
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料维护";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMaterialmaintenance(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料维护";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMaterialmaintenance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.itemLevel = this.form.itemLevelFirst + '' + this.form.itemLevelSecond
            this.form.keyParameters = this.keyParameters
            addShenhe(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料维护编号为"' + ids + '"的数据项？').then(function () {
        return delMaterialmaintenance(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gyl/materialmaintenance/export', {
        ...this.queryParams
      }, `materialmaintenance_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('gyl/materialmaintenance/importTemplate', {
      }, `materialmaintenance_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // getSelectData() {
    //   const childComputedValue = this.$refs.childRef.getSelectData();
    //   console.log(childComputedValue);
    // },
    //将驼峰命名改成下划线
    getKebabCase(str) {
      let temp = str.replace(/[A-Z]/g, function(i) {
        return '_' + i.toLowerCase();
      })
      if (temp.slice(0,1) === '_') {
        temp = temp.slice(1);   //如果首字母是大写，执行replace时会多一个_，需要去掉
      }
      return temp;
    },
    //获取表单数据
    rowsol(column){
      this.opens=true;
      this.list.itemName = this.getKebabCase(column.column)
      console.log(this.list.itemName)
      this.list.ids= column.List
    },
    //发送修改某一列请求
    submitList(){
      PutMaterialmaintenance(JSON.stringify(this.list)).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.opens = false;
        this.reset();
        this.getList();
      })
    },
    blurs(){
      if(this.Shuju.fontSize==''||this.Shuju.Height=='')
      {
        this.Shuju.Height=60
        this.Shuju.fontSize = 12
      }
      const Size =  this.$refs.childRef.changeSize();
      console.log(Size)
    },
    //MySelect中的编辑数据
    editValue(item){
      if(item.type==='category') {
        this.form.materialName = item.value
        item.value = this.listMaterials.filter(Meterial => {
        return Meterial.materialSubclass4===item.value?Meterial.groupCode:''
      })[0].groupCode}
      this.form[item.type] = item.value
    },
    //MyObject中的修改输入值
    editItemValue(obj){
      this.leiItems.map( item => {
        if(item.id === obj.id) item.data = obj.value
        return item
      })
    },
    //获取初始被选择列表数组
    async getInitDataList(){
      await listMaterials().then( res => {
        res.rows.forEach(item => {
          this.categorys.push(item.materialSubclass4)
          this.listMaterials.push(item)
        })
      })
      await listMaterialmaintenance().then( res => {
        res.rows.forEach(item => !this.brands.includes(item.brand) && this.brands.push(item.brand))
      })

      await listRulesTotal().then( res => {
        let i = -1
        res.rows.forEach(obj => {
          if(obj.elementName === '大类') {
            i+=1
            !this.daleis.includes(obj.ruleValue) && this.daleis.push(obj.ruleValue)
            this.totalList[i] = []
          }
          this.totalList[i].push(obj)
        })
      })
    },
    //获取物料增加中的选项配置接口中的数据进行存储
    async getGYLValueSelect(){
      await listGylvalueTotal().then( res => {
        this.OptionsDefineTotals = [...res.rows]
        this.OptionsDefineTotals.forEach(item => {
          this.OptionsKeyValue[item.elementName]?'':this.OptionsKeyValue[item.elementName] = []
          !this.OptionsKeyValue[item.elementName].includes(item.describeVlue) && this.OptionsKeyValue[item.elementName].push(item.describeVlue)
        })
      })
    }
  }
};
</script>
<style lang="css" scoped>
@import "../CSS/style.css";
::v-deep .el-input__inner {
  height: 29px;
  line-height: 29px;
}
::v-deep .vxe-toolbar{
  margin-top: -18px;
}
</style>
